package com.soft.springhrms.config;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.soft.springhrms.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");  // 从请求头获取 Token

        if (token == null || !JwtUtil.isTokenValid(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  // 如果没有 Token 或 Token 无效，返回 401
            response.getWriter().write("Unauthorized");  // 返回未授权信息
            return false;
        }

        // 解析 JWT，获取其中的 Claims（例如：userId 和 roleId）
        DecodedJWT decodedJWT = JwtUtil.parseToken(token);
        Long userId = decodedJWT.getClaim("userId").asLong();
        Integer roleId = decodedJWT.getClaim("roleId").asInt();

        // 将用户信息存储在请求上下文中，供后续的权限判断使用
        request.setAttribute("userId", userId);
        request.setAttribute("roleId", roleId);

        return true;
    }
}
